package com.thinkgem.jeesite.modules.sys.web;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.product.entity.attribute.TbProductAttribute;
import com.thinkgem.jeesite.modules.product.entity.dict.TbProductAttributeDict;
import com.thinkgem.jeesite.modules.product.service.attribute.TbProductAttributeService;
import com.thinkgem.jeesite.modules.product.service.dict.TbProductAttributeDictService;
import com.thinkgem.jeesite.modules.sys.dao.TbAttachmentMapper;
import com.thinkgem.jeesite.modules.sys.entity.*;
import com.thinkgem.jeesite.modules.sys.service.OverSeasProductService;
import com.thinkgem.jeesite.modules.sys.service.TbAgentProductService;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/*
 * Created by jyy on 2016/10/21 0021.
 */


@Controller
@RequestMapping(value = "${adminPath}/sys/overseas")
public class TbOverseasProductController extends BaseController {

    @Autowired
    private  OverSeasProductService overSeasProductService;
    @Autowired
    private TbAgentProductService tbAgentProductService;

    @Autowired
    private TbProductAttributeService tbProductAttributeService;

    @Autowired
    private TbAttachmentMapper tbAttachmentMapper;

    @Autowired
    private TbProductAttributeDictService productAttributeDictService;


    /**
     * 执行所有方法前先获取tbproduct
     *
     * @param id
     * @return
     */
    @ModelAttribute
    public TbProduct get(@RequestParam(required = false) Integer id) {
        if (null != id) {
            return overSeasProductService.get(id);
        } else {
            return new TbProduct();
        }
    }


    /**
     * 跳转到编辑商品页面
     *
     * @param tbProduct
     * @param model
     * @return
     */
    @RequestMapping(value = "form")
    public String form(TbProduct tbProduct, Model model) {
        if (tbProduct.getId() != null && !"".equals(tbProduct.getId())) {
            TbCategory tbCategory = overSeasProductService.getTbCategory(tbProduct.getCategoryId());
            model.addAttribute("category", tbCategory);
            List<TbShopProduct> list=overSeasProductService.selectShopProductByProductId(tbProduct.getId());
            model.addAttribute("list",list);
            model.addAttribute("listLength",list.size());
            //pics
            List<TbAttachment> tbAttachments = this.tbAttachmentMapper.selectByFkId(tbProduct.getId());
            model.addAttribute("tbAttachments", tbAttachments);

        }


        tbProduct = this.overSeasProductService.get(tbProduct.getId());
        if(tbProduct!=null){
            model.addAttribute("tbProduct", tbProduct);
        }else{
            TbProduct product = new TbProduct();
            model.addAttribute("tbProduct", product);
        }
        TbProductAttributeDict dict = new TbProductAttributeDict();
        dict.setCode("type");
        List<TbProductAttributeDict> productAttributeDicts = productAttributeDictService.findList(dict);
        model.addAttribute("attribute", productAttributeDicts);
        return "modules/sys/showOverSeasProductForm";
    }

    /**
     * 查询所有商品——分页
     *
     * @param tbProduct
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping(value = {"showOverSeasProductList", ""})
    public String showProductList(TbProduct tbProduct, HttpServletRequest request, HttpServletResponse response, Model model) {
        User user = UserUtils.getUser();
        tbProduct.setAgentId(user.getId());
        Page<TbProduct> page = overSeasProductService.findProductByPage(new Page<TbProduct>(request, response), tbProduct);
        model.addAttribute("page", page);
        if(page.getList().size()==0){
            model.addAttribute("message1","无查询结果");
        }
        return "modules/sys/showOverSeasProductList";

    }
    /**
     * 增加或更改商品
     * @param tbProduct
     * @param model
     * @param redirectAttributes
     * @return
     */
    @RequestMapping(value = "productEdit")
    public String productEdit(TbProduct tbProduct, Model model, RedirectAttributes redirectAttributes,
                              HttpServletRequest request) {
        User currentUser = UserUtils.getUser();
        String storeNum = request.getParameter("storeNum");
        String alertStoreNum = request.getParameter("alertStoreNum");
        if (StringUtils.isNotBlank(tbProduct.getTitle())) {
            tbProduct.setProductDesc(StringEscapeUtils.unescapeHtml4(tbProduct.getProductDesc()));
            int id = overSeasProductService.saveOrUpdateProduct(tbProduct, storeNum, alertStoreNum);
            if(id==0){
                addMessage(redirectAttributes, "请您维护自己的店铺，没有店铺，不能添加商品");
            }else{
                if (tbProduct.getUploadUrl() != null && tbProduct.getUploadUrl().size() > 0) {
                    overSeasProductService.insertProductImg(id, tbProduct.getUploadUrl());
                }
                model.addAttribute("message", "保存商品信息成功");
                addMessage(redirectAttributes, "编辑商品成功");
            }

        }

        return "redirect:" + adminPath + "/sys/overseas/showOverSeasProductList";
    }

    //废弃
    @RequestMapping(value = "upload")
    public void photoUpload(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/html;charset=UTF-8");
        try {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            MultipartFile file = null;
            MultiValueMap<String, MultipartFile> multiFileMap = multipartRequest.getMultiFileMap();
            List<String> uploadUrl = overSeasProductService.uploadMulFile(multiFileMap, request);
            response.getWriter().print(request.getParameter("id"));
            response.getWriter().flush();
            response.getWriter().close();
        } catch (Exception e) {

        }
    }

    @RequestMapping(value = "delete")
    public String delete(TbProduct tbProduct, RedirectAttributes redirectAttributes) {
        if (Global.isDemoMode()) {
            addMessage(redirectAttributes, "演示模式，不允许操作！");
            return "redirect:" + adminPath + "/sys/product/showProductList/?repage";
        }
        //TbAgentProduct tbAgentProduct = tbAgentProductService.selectByProductId(tbProduct.getId());
        TbShopProduct tbShopProduct=overSeasProductService.selectTbshopProductById(tbProduct.getId());
        if(tbShopProduct!=null&&"1".equals(tbShopProduct.getStatus())){
            addMessage(redirectAttributes, "上架商品不允许删除！");
        }else {
            overSeasProductService.delete(tbProduct);
            addMessage(redirectAttributes, "删除商品成功");
        }
            return "redirect:" + adminPath + "/sys/overseas/showOverSeasProductList";
    }
    @RequestMapping("/checkBarcode")
    public void checkBarcode(HttpServletRequest request, HttpServletResponse response,String barcode) {
        response.setContentType("text/html;charset=UTF-8");
        TbProduct tbProduct = overSeasProductService.selectProductBybarcode(barcode);
        try {
            if (tbProduct != null) {
                response.getWriter().print(tbProduct.getId());
            } else {
                response.getWriter().print("0");
            }
            response.getWriter().flush();
            response.getWriter().close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
